package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class CongressionalDistrictService {

    def jurisdictionService
    def stateService

    static transactional = true

    /* CRUD */
    public CongressionalDistrict create(CongressionalDistrict cd) throws DAOException{
        cd.state.addToCongressionalDistricts(cd)
        stateService.save(cd.state)
        save(cd)
        return cd
    }
    public void save(CongressionalDistrict cd) throws DAOException{
        ServiceUtils.save(cd)
    }
    public void save(CongressionalDistrict cd, boolean flush) throws DAOException{
        ServiceUtils.save(cd, flush)
    }
    public void delete(CongressionalDistrict cd){
        if(cd == null){
            return
        }
        if(cd.state?.congressionalDistricts?.contains(cd)){
            cd.state.congressionalDistricts.remove(cd)
        }
        cd.delete(flush:true)
    }
    public CongressionalDistrict merge(CongressionalDistrict cd){
        return cd.merge()
    }
    public CongressionalDistrict get(String cdId){
        return get(Long.parseLong(cdId))
    }
    public CongressionalDistrict get(long cdId){
        return CongressionalDistrict.get(cdId)
    }
    public Set<CongressionalDistrict> getAll(){
        return CongressionalDistrict.findAll()
    }
    /* END CRUD */

    public CongressionalDistrict getByNameAndStateOrCreate(String name, State state, String longName){
        CongressionalDistrict cd = getByNameAndState(name, state)
        if(cd == null){
            cd = new CongressionalDistrict(
                name:name,
                longName:longName,
                state:state
            )
            cd = create(cd)
        }
        return cd
    }

    public CongressionalDistrict getByNameAndState(String name, State state){
        CongressionalDistrict cd = CongressionalDistrict.findByNameAndState(name, state)
        return cd
    }
}